const axios = require('axios');
const dotenv = require('dotenv');

dotenv.config();

// 和风天气API配置
const QWEATHER_API_KEY = process.env.QWEATHER_API_KEY || '49a317bc4b924b66b7343ad492b88214';
const QWEATHER_API_HOST = process.env.QWEATHER_API_HOST || 'pn6yvxdqm8.re.qweatherapi.com';
const QWEATHER_BASE_URL = `https://${QWEATHER_API_HOST}/v7`;
const QWEATHER_GEO_URL = `https://${QWEATHER_API_HOST}/geo/v2/city`;

// 创建带有默认请求头的axios实例
const qweatherAxios = axios.create({
  headers: {
    'X-QW-Api-Key': QWEATHER_API_KEY,
    'Accept-Encoding': 'gzip'
  }
});

/**
 * 获取实时天气数据
 * @param {string} location - 城市名称或经纬度坐标
 * @returns {Promise<Object>} 天气数据
 */
async function getRealTimeWeather(location) {
  try {
    console.log(`正在请求实时天气数据: ${QWEATHER_BASE_URL}/weather/now?location=${location}`);
    const response = await qweatherAxios.get(`${QWEATHER_BASE_URL}/weather/now`, {
      params: {
        location,
        lang: 'zh',
        unit: 'm'
      }
    });

    if (response.data.code === '200') {
      return response.data;
    } else {
      throw new Error(`和风天气API错误: ${response.data.code}`);
    }
  } catch (error) {
    console.error('获取实时天气数据失败:', error.message);
    throw error;
  }
}

/**
 * 获取未来天气预报
 * @param {string} location - 城市ID或经纬度坐标
 * @param {number} days - 天数，可选值：3、7、10、15、30
 * @returns {Promise<Object>} 天气预报数据
 */
async function getWeatherForecast(location, days = 7) {
  try {
    // 确保days参数格式正确
    const daysStr = `${days}d`;
    if (!['3d', '7d', '10d', '15d', '30d'].includes(daysStr)) {
      throw new Error('预报天数只能是3、7、10、15或30');
    }

    console.log(`正在请求天气预报数据: ${QWEATHER_BASE_URL}/weather/${daysStr}?location=${location}`);
    const response = await qweatherAxios.get(`${QWEATHER_BASE_URL}/weather/${daysStr}`, {
      params: {
        location,
        lang: 'zh',
        unit: 'm'
      }
    });

    if (response.data.code === '200') {
      return response.data;
    } else {
      throw new Error(`和风天气API错误: ${response.data.code}`);
    }
  } catch (error) {
    console.error('获取天气预报数据失败:', error.message);
    throw error;
  }
}

/**
 * 城市搜索
 * @param {string} location - 城市名称，支持模糊搜索
 * @param {Object} options - 额外选项
 * @param {string} [options.adm] - 城市的上级行政区划
 * @param {string} [options.range] - 搜索范围，国家代码
 * @param {number} [options.number] - 返回结果数量，默认10
 * @returns {Promise<Object>} 城市信息
 */
async function searchCity(location, options = {}) {
  try {
    console.log(`正在请求城市查询数据: ${QWEATHER_GEO_URL}/lookup?location=${location}`);
    const response = await qweatherAxios.get(`${QWEATHER_GEO_URL}/lookup`, {
      params: {
        location,
        adm: options.adm,
        range: options.range || 'cn',
        number: options.number || 10,
        lang: 'zh'
      }
    });

    if (response.data.code === '200') {
      return response.data;
    } else {
      throw new Error(`和风天气API错误: ${response.data.code}`);
    }
  } catch (error) {
    console.error('城市搜索失败:', error.message);
    throw error;
  }
}

/**
 * 获取热门城市列表
 * @param {Object} options - 额外选项
 * @param {string} [options.range] - 搜索范围，国家代码
 * @param {number} [options.number] - 返回结果数量，默认10
 * @returns {Promise<Object>} 热门城市列表
 */
async function getTopCities(options = {}) {
  try {
    console.log(`正在请求热门城市数据: ${QWEATHER_GEO_URL}/top`);
    const response = await qweatherAxios.get(`${QWEATHER_GEO_URL}/top`, {
      params: {
        range: options.range || 'cn',
        number: options.number || 10,
        lang: 'zh'
      }
    });

    if (response.data.code === '200') {
      return response.data;
    } else {
      throw new Error(`和风天气API错误: ${response.data.code}`);
    }
  } catch (error) {
    console.error('获取热门城市列表失败:', error.message);
    throw error;
  }
}

/**
 * 获取空气质量
 * @param {string} location - 城市名称或经纬度坐标
 * @returns {Promise<Object>} 空气质量数据
 */
async function getAirQuality(location) {
  try {
    console.log(`正在请求空气质量数据: ${QWEATHER_BASE_URL}/air/now?location=${location}`);
    const response = await qweatherAxios.get(`${QWEATHER_BASE_URL}/air/now`, {
      params: {
        location,
        lang: 'zh'
      }
    });

    if (response.data.code === '200') {
      return response.data;
    } else {
      throw new Error(`和风天气API错误: ${response.data.code}`);
    }
  } catch (error) {
    console.error('获取空气质量数据失败:', error.message);
    throw error;
  }
}

/**
 * 获取天气灾害预警信息
 * @param {string} location - 城市ID或经纬度坐标
 * @returns {Promise<Object>} 预警信息数据
 */
async function getWeatherWarnings(location) {
  try {
    console.log(`正在请求天气预警数据: ${QWEATHER_BASE_URL}/warning/now?location=${location}`);
    const response = await qweatherAxios.get(`${QWEATHER_BASE_URL}/warning/now`, {
      params: {
        location,
        lang: 'zh'
      }
    });

    if (response.data.code === '200') {
      return response.data;
    } else {
      throw new Error(`和风天气API错误: ${response.data.code}`);
    }
  } catch (error) {
    console.error('获取天气预警数据失败:', error.message);
    throw error;
  }
}

/**
 * 天气图标代码转换为文字描述
 * @param {string} iconCode - 和风天气图标代码
 * @returns {string} 天气描述
 */
function iconCodeToWeatherCondition(iconCode) {
  const iconMap = {
    '100': '晴',
    '101': '多云',
    '102': '多云',
    '103': '多云',
    '104': '阴',
    '150': '晴',
    '151': '多云',
    '152': '多云',
    '153': '多云',
    '300': '小雨',
    '301': '小雨',
    '302': '中雨',
    '303': '大雨',
    '304': '暴雨',
    '305': '小雨',
    '306': '中雨',
    '307': '大雨',
    '308': '暴雨',
    '309': '小雨',
    '310': '暴雨',
    '311': '大雨',
    '312': '暴雨',
    '313': '小雨',
    '314': '小雨',
    '315': '中雨',
    '316': '大雨',
    '317': '暴雨',
    '318': '大雨',
    '350': '小雨',
    '351': '小雨',
    '399': '小雨',
    '400': '小雪',
    '401': '中雪',
    '402': '大雪',
    '403': '暴雪',
    '404': '雨夹雪',
    '405': '雨夹雪',
    '406': '雨夹雪',
    '407': '小雨',
    '408': '中雨',
    '409': '暴雨',
    '410': '暴雨',
    '456': '小雨',
    '457': '中雨',
    '499': '小雪',
    '500': '雾',
    '501': '雾',
    '502': '雾',
    '503': '雾',
    '504': '雾',
    '507': '雾',
    '508': '雾',
    '509': '雾',
    '510': '雾',
    '511': '雾',
    '512': '雾',
    '513': '雾',
    '514': '雾',
    '515': '雾',
    '900': '晴',
    '901': '多云',
    '999': '晴'
  };

  return iconMap[iconCode] || '晴';
}

/**
 * 转换和风天气API响应为应用格式
 * @param {Object} realTimeData - 实时天气数据
 * @param {Object} forecastData - 天气预报数据
 * @param {Object} airQualityData - 空气质量数据
 * @returns {Object} 转换后的天气数据
 */
function convertWeatherData(realTimeData, forecastData, airQualityData) {
  // 提取实时天气数据
  const now = realTimeData.now;
  const weatherCondition = iconCodeToWeatherCondition(now.icon);
  
  // 提取空气质量数据
  const air = airQualityData ? airQualityData.now : null;
  
  // 提取预报数据
  const dailyForecast = forecastData ? forecastData.daily : [];
  const forecast = dailyForecast.map(day => ({
    date: day.fxDate,
    fxDate: day.fxDate, 
    sunrise: day.sunrise || '',
    sunset: day.sunset || '',
    moonrise: day.moonrise || '',
    moonset: day.moonset || '',
    moonPhase: day.moonPhase || '',
    moonPhaseIcon: day.moonPhaseIcon || '',
    temperatureHigh: parseFloat(day.tempMax),
    temperatureLow: parseFloat(day.tempMin),
    weatherCondition: iconCodeToWeatherCondition(day.iconDay),
    weatherConditionNight: iconCodeToWeatherCondition(day.iconNight),
    iconDay: day.iconDay || '',
    textDay: day.textDay || '',
    iconNight: day.iconNight || '',
    textNight: day.textNight || '',
    wind360Day: parseInt(day.wind360Day) || 0,
    windDirDay: day.windDirDay || '',
    windScaleDay: day.windScaleDay || '',
    windSpeedDay: parseFloat(day.windSpeedDay) || 0,
    wind360Night: parseInt(day.wind360Night) || 0,
    windDirNight: day.windDirNight || '',
    windScaleNight: day.windScaleNight || '',
    windSpeedNight: parseFloat(day.windSpeedNight) || 0,
    windSpeed: parseFloat(day.windSpeedDay) || 0,
    windDirection: day.windDirDay || '',
    humidity: parseFloat(day.humidity) || 0,
    precipitation: parseFloat(day.precip) || 0,
    pressure: parseFloat(day.pressure) || 0,
    visibility: parseFloat(day.vis) || 0,
    cloud: parseInt(day.cloud) || 0,
    uvIndex: day.uvIndex || '0',
    probability: parseFloat(day.precip) > 0 ? 80 : 10
  }));

  // 确定空气质量级别
  let airQualityLevel = '优';
  if (air) {
    const aqi = parseInt(air.aqi);
    if (aqi <= 50) airQualityLevel = '优';
    else if (aqi <= 100) airQualityLevel = '良';
    else if (aqi <= 150) airQualityLevel = '轻度污染';
    else if (aqi <= 200) airQualityLevel = '中度污染';
    else if (aqi <= 300) airQualityLevel = '重度污染';
    else airQualityLevel = '严重污染';
  }

  // 构建结果数据
  return {
    temperature: parseFloat(now.temp),
    temperatureFeelsLike: parseFloat(now.feelsLike),
    temperatureHigh: forecast.length > 0 ? forecast[0].temperatureHigh : null,
    temperatureLow: forecast.length > 0 ? forecast[0].temperatureLow : null,
    humidity: parseFloat(now.humidity),
    precip: parseFloat(now.precip) || 0,
    pressure: parseFloat(now.pressure) || 0,
    vis: parseFloat(now.vis) || 0,
    cloud: parseInt(now.cloud) || 0,
    dew: parseFloat(now.dew) || 0,
    windSpeed: parseFloat(now.windSpeed),
    windDirection: now.windDir,
    wind360: parseInt(now.wind360) || 0,
    windScale: now.windScale || '',
    weatherCondition: weatherCondition,
    icon: now.icon || '',
    text: now.text || weatherCondition,
    aqi: air ? parseInt(air.aqi) : null,
    airQualityLevel: airQualityLevel,
    pm25: air ? parseFloat(air.pm2p5) : null,
    pm10: air ? parseFloat(air.pm10) : null,
    obsTime: now.obsTime,
    updateTime: now.obsTime,
    fxLink: realTimeData.fxLink || '',
    forecast: forecast
  };
}

module.exports = {
  getRealTimeWeather,
  getWeatherForecast,
  searchCity,
  getTopCities,
  getAirQuality,
  getWeatherWarnings,
  iconCodeToWeatherCondition,
  convertWeatherData
}; 